import { FC, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import './login.css';
import loginMainPicture from '../../assets/images/LOGIN-MAIN.png';
import { login } from '../../api';

const Login: FC = () => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    const navigate = useNavigate();
    const location = useLocation();

    // 获取重定向的目标路径，如果没有则默认为首页
    const from = location.state?.from || '/student';

    const handleLogin = async (e: React.FormEvent) => {
        e.preventDefault();

        // 表单验证
        if (!username || !username.trim()) {
            setError('请输入用户名');
            return;
        }

        if (!password || !password.trim()) {
            setError('请输入密码');
            return;
        }

        setError('');

        setLoading(true);

        try {
            // 调用登录API
            const response = await login(username, password);
            console.log('登录成功:', response);

            // 登录成功后跳转到原来的页面或默认页面
            navigate(from, { replace: true });
        } catch (err) {
            // 处理错误
            console.error('登录失败:', err);
            setError(err instanceof Error ? err.message : '登录失败，请检查用户名和密码');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="login-container">
            {/* 毛玻璃 */}
            <div className="login-card-container">
                <div className="login-card">
                    <div className="login-image">
                        <img src={loginMainPicture} alt="Login" />
                    </div>
                    <div className="login-form">
                        <div className="login-title" style={{ textAlign: 'center' }}>
                            Student Management System
                        </div>
                        <div className="login-subtitle" style={{ textAlign: 'center' }}>
                            CDC Login
                        </div>

                        {error && <div className="error-message">{error}</div>}

                        <form onSubmit={handleLogin}>
                            <div className="form-group">
                                <label className="form-label">Username</label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={username}
                                    onChange={(e) => setUsername(e.target.value)}
                                    required
                                    disabled={loading}
                                />
                            </div>

                            <div className="form-group">
                                <label className="form-label">Password</label>
                                <input
                                    type="password"
                                    className="form-input"
                                    value={password}
                                    onChange={(e) => setPassword(e.target.value)}
                                    required
                                    disabled={loading}
                                />
                            </div>

                            <button type="submit" className="login-button" disabled={loading}>
                                {loading ? 'Login...' : 'Login'}
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Login;
